<?php

namespace addons\aliyunsms\library;

use addons\aliyunsms\library\sdk\Client;
use addons\aliyunsms\library\sdk\ClientNew;

class Aliyunsms
{
    private $_params = [];
    protected $error = '';
    protected $config = [];
    protected static $instance = null;

    public function __construct($options = [])
    {

        if ($config = get_addon_config('aliyunsms')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 单例
     * @param array $options 参数
     * @return Aliyunsms
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * 立即发送短信
     *
     * @return boolean
     */
    public function send()
    {
        $this->error = '';
        $params = $this->_params();

        try {
            // 构建endpoint
            $endpoint = 'dysmsapi.ap-southeast-1.aliyuncs.com';
            // dump($endpoint);exit;

            // dump(strpos($params['mobile'], '86'));exit;

            // 创建客户端
            if (strpos($params['mobile'], '86') === false) {
                $senderid = '';
                $client = new ClientNew(
                    $this->config['access_key_id'],
                    $this->config['access_key_secret'],
                    $endpoint
                );

                $result = $client->sendSms(
                    $params['mobile'],
                    $senderid,
                    $params['msg']
                );
            } else {
                $client = new Client(
                    $this->config['access_key_id'],
                    $this->config['access_key_secret'],
                    $endpoint
                );

                // 判断是验证码还是通知短信
                $templateCode = $this->config['template_code'];
                $templateParam = [];

                // 如果是验证码短信，提取验证码
                if (isset($params['code'])) {
                    $templateParam = ['code' => $params['code']];
                } else {
                    // 通知短信，使用通知模板
                    if (!empty($this->config['notice_template_code'])) {
                        $templateCode = $this->config['notice_template_code'];
                    }
                    // 对于通知短信，可能需要根据模板要求传递参数
                    // 这里可以根据实际模板要求进行调整
                }

                // 发送短信
                $result = $client->sendSms(
                    $params['mobile'],
                    $this->config['sign_name'],
                    $templateCode,
                    $templateParam
                );
            }

            // dump($result);
            // exit;

            // 检查结果
            if (isset($result['RequestId']) && $result['ResponseCode'] === 'OK') {
                return true;
            } else {
                $this->error = isset($result['Message']) ? $result['Message'] : '发送失败';
                return false;
            }
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    private function _params()
    {
        return array_merge([], $this->_params);
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 接收手机
     * @param   string $mobile 手机号码
     * @return Aliyunsms
     */
    public function mobile($mobile = '')
    {
        $this->_params['mobile'] = $mobile;
        return $this;
    }

    /**
     * 短信内容
     * @param   string $msg 短信内容
     * @return Aliyunsms
     */
    public function msg($msg = '')
    {
        // 对于阿里云短信，内容由模板控制，这里主要用于验证码提取
        if (preg_match('/验证码[是：:]\s*(\d+)/', $msg, $matches)) {
            $this->_params['code'] = $matches[1];
        } else {
            // 通知短信，保存原始内容
            $this->_params['msg'] = $msg;
        }
        return $this;
    }
}
